package com.express.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.express.basic.token.DefaultTokenManager;
import com.express.dao.pojo.BizUser;
import com.express.param.AddUserReq;
import com.express.param.FindUserInfoReq;
import com.express.param.LoginUserReq;
import com.express.param.MsgResponse;
import com.express.service.BizUserService;
import com.google.common.collect.Maps;

@Controller
@RequestMapping("/user")
public class UserCtrl extends AbstractController{

	private static final Logger logger = Logger.getLogger(UserCtrl.class);
	
	@Autowired
	private BizUserService bizUserService;
	@Autowired
	private DefaultTokenManager tokenManager;
	
	/**
	 * 
	* @Title: login 
	* @Description: 登录接口，返回token，需要验证的接口，应在header里面设置token，token有时效性
	* @param @param req
	* @param @param request
	* @param @return    
	* @return MsgResponse    
	* @throws
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	@ResponseBody
	public MsgResponse login(@RequestBody @Valid LoginUserReq req,HttpServletRequest request){
		MsgResponse msgResponse = new MsgResponse();
		
		BizUser bizUser = bizUserService.login(req);
		String token = tokenManager.createToken(bizUser.getId());
		
		Map<String, Object> dataMap = Maps.newHashMap();
		dataMap.put("user", bizUser);
		dataMap.put("token", token);
		msgResponse.setData(dataMap);
		return msgResponse;
	}

	/**
	 * 
	* @Title: register 
	* @Description: 注册接口
	* @param @param req
	* @param @param request
	* @param @return    
	* @return MsgResponse    
	* @throws
	 */
	@RequestMapping(value="/register",method=RequestMethod.POST)
	@ResponseBody
	public MsgResponse register(@RequestBody @Valid AddUserReq req,HttpServletRequest request){
		MsgResponse msgResponse = new MsgResponse();
		
		BizUser bizUser = bizUserService.register(req);
		msgResponse.setData(bizUser);
		return msgResponse;
	}
	
	/**
	 * 
	* @Title: findUserInfo 
	* @Description: 根据token查询用户id
	* @param @param req
	* @param @param request
	* @param @return    
	* @return MsgResponse    
	* @throws
	 */
	@RequestMapping(value="/findUserInfo",method=RequestMethod.POST)
	@ResponseBody
	public MsgResponse findUserInfo(@RequestBody @Valid FindUserInfoReq req,HttpServletRequest request){
		MsgResponse msgResponse = new MsgResponse();
		//解析token，并讲token解析后的userId设置到请求体的对象中
		needToken(req, request);
		logger.info(String.format("解析出来的userId：{%s}", req.getUserId()));
		msgResponse.setData(req.getUserId());
		return msgResponse;
	}
	
	
}
